<?php
namespace app\admin\controller;

use think\facade\Db;
use think\facade\View;
use app\common\logic\OrderLogic;
class Users extends Base {
    public function index(){
        //$map = $this->_search();
        $wallet_arr = logic('Wallet')->getName();
        unset($wallet_arr['s_money']);
        if(IS_AJAX){
            $page = input('page');
            $limit = input('limit')?:15;
            $map = [];
            if(input('user_id')){
                $map['u.user_id'] = input('user_id');
            }
            if(input('username')){
                $map['u.username'] = input('username');
            }
            if(input('level')){
                $map['u.level'] = input('level');
            }
            if(input('level1')){
                $map['u.level1'] = input('level1');
            }
            if(input('time_start') && input('time_end')){
                $time_start = strtotime(input('time_start'));
                $time_end = strtotime(input('time_end'));
                $map['reg_time'] = ['between',[$time_start,$time_end]];
            }
            $count = Db::name('users')->alias('u')->where($map)->count();

            $field = 'u.user_id,u.username,u.mobile,u.nickname,u.level,u.tjr_name,u.gl_username,u.is_lock,u.email,u.reg_time,u.team_yeji,u.level1,u.is_fuwu';
            foreach($wallet_arr as $wallet_key=>$wallet_name){
                $field .= ',w.'.$wallet_key;
            }
            $list = Db::name('users')
                ->alias('u')
                ->join('wallet w','u.user_id=w.user_id')
                ->field($field)
                ->where($map)
                ->order('u.user_id desc ')
                ->page($page,$limit)
                ->select();
            $level_arr = Db::name('user_level')->column('level_name','rank');
            $level1_arr = Db::name('user_level1')->column('level_name','rank');
            foreach($list as $k=>$v){
                $v['level_name'] = $level_arr[$v['level']];
                $v['level1_name'] = $level1_arr[$v['level1']];
                $v['reg_time'] = date('Y-m-d H:i:s',$v['reg_time']);
                $list[$k] = $v;
            }
            $total = Db::name('users')
                ->alias('u')
                ->join('wallet w','u.user_id=w.user_id')
                ->where($map)
                ->field('sum(money) money,sum(gouwuquan) gouwuquan,sum(w.shouyi) shouyi')
                ->find();
            return json(['code'=>0,'msg'=>'查询成功','count'=>$count,'data'=>$list,'totalRow'=>$total]);
        }
        $level_arr = Db::name('user_level')->field('level_name,rank')->select();
        View::assign('level_arr',$level_arr);

        $level1_arr = Db::name('user_level1')->field('level_name,rank')->select();
        View::assign('level1_arr',$level1_arr);

        View::assign('wallet_arr',$wallet_arr);
        return View::fetch();
    }

    /**
     * 会员详细信息查看
     */
    public function detail(){
        $uid = input('id');
        $user = Db::name('Users')->where('user_id',$uid)->find();
        //获取可查看项
        $view = tpCache('userdata.view');
        $only = tpCache('userdata.only');
        $userdata = config('userdata');
        $edit = tpCache('userdata.edit');


        if (IS_POST) {
            $post = input('post.');
            unset($post['id']);
            //唯一
            foreach($only as $key=>$num){
                if($num!=0 && in_array($key,$view)){
                    if (isset($post[$key]) && $post[$key] != '') {
                        $c = Db::name('Users')->where([$key => $post[$key], 'user_id' => ['<>', $uid]])->count();
                        if ($c >= $num) {
                            //$this->error($userdata[$key] . '已达上限');
                            return json(['status'=>false,'msg'=>$userdata[$key] . '已达上限']);
                        }
                    }
                }
            }

            //密码
            if($post['password']==''){
                unset($post['password']);
            }else{
                if($post['password']!=$post['password2']){
                    return json(['status'=>false,'msg'=>'两次密码不一致']);
                }
                if(strlen($post['password'])<6){
                    return json(['status'=>false,'msg'=>'密码不能少于6位数']);
                }
                $post['password'] = encrypt($post['password']);
            }
            //密码
            if($post['paypwd']==''){
                unset($post['paypwd']);
            }else{
                if(strlen($post['paypwd'])<6){
                    $this->error('二级密码不能少于6位数');
                }
                $post['paypwd'] = encrypt($post['paypwd']);
            }


            Db::startTrans();
            $data_u = [];
            $data_u['mobile'] = $post['mobile'];
            $data_u['nickname'] = $post['nickname'];
            $data_u['level'] = $post['level'];
            $data_u['level1'] = $post['level1'];
            if(isset($post['password'])){
                $data_u['password'] = $post['password'];
            }
            if(isset($post['paypwd'])) {
                $data_u['password'] = $post['paypwd'];
            }
            $rs = Db::name('Users')->where('user_id',$uid)->update($data_u);
            if($post['level'] && $post['level']!=$user['level']){
                $curtime = getCurTime();
                //插入升级记录
                $insert = array();
                $insert['username'] = $user['username'];
                $insert['old'] = $user['level'];
                $insert['new'] = $post['level'];
                $insert['w_time'] = $curtime;
                $insert['desc'] = "后台修改";
                $insert['admin_id'] = session('admin_id');
                $rs = Db::name('level_log')->insert($insert);
                if(!$rs){
                    return json(['status'=>0,'msg'=>'添加升级记录失败']);
                }
            }
            if($post['level1'] && $post['level1']!=$user['level1']){
                $curtime = getCurTime();
                //插入升级记录
                $insert = array();
                $insert['username'] = $user['username'];
                $insert['old'] = $user['level1'];
                $insert['new'] = $post['level1'];
                $insert['w_time'] = $curtime;
                $insert['desc'] = "后台修改";
                $insert['admin_id'] = session('admin_id');
                $rs = Db::name('level_log1')->insert($insert);
                if(!$rs){
                    return json(['status'=>0,'msg'=>'添加升级记录失败']);
                }
            }
            Db::commit();
            if ($rs===false)
                $this->error("保存失败");

            return json(['status'=>true,'msg'=>'操作成功']);
            $this->success("操作成功",U('Users/index'));
        }else{

            View::assign('user',$user);
            $level_arr = Db::name('user_level')->where('1=1')->select();
            View::assign('level_arr',$level_arr);

            $level1_arr = Db::name('user_level1')->where('1=1')->select();
            View::assign('level1_arr',$level1_arr);
        }

        View::assign('view',$view);
        View::assign('userdata',$userdata);
        View::assign('edit',$edit);
        return View::fetch();
    }

    /**
     * 用户收货地址查看
     */
    public function address(){
        $user_id = input('get.user_id');
        if(IS_AJAX){
            $page = input('page');
            $limit = input('limit')?:15;
            $map = [];
            if(input('user_id')){
                $map['u.user_id'] = input('user_id');
            }
            if(input('username')){
                $map['u.username'] = input('username');
            }
            $count = Db::name('users')->alias('u')->where($map)->count();
            $regionList = get_region_list();
            $field = 'a.*,u.username,u.nickname';
            $list = Db::name('user_address')
                ->alias('a')
                ->join('users u','u.user_id = a.user_id')
                ->field($field)
                ->where($map)
                ->order('a.address_id desc ')
                ->page($page,$limit)
                ->select()->toArray();
            foreach($list as $k=>$v){
                $v['province_name'] = $regionList[$v['province']]??'';
                $v['city_name'] = $regionList[$v['city']]??'';
                $v['district_name'] = $regionList[$v['district']]??'';
                //$v['reg_time'] = date('Y-m-d H:i:s',$v['reg_time']);
                $list[$k] = $v;
            }

            return json(['code'=>0,'msg'=>'查询成功','count'=>$count,'data'=>$list]);
        }
        return View::fetch();
    }

    /**
     *
     * @time 2016/08/31
     * @author dyr
     * 发送站内信
     */
    public function sendMessage()
    {
        $user_id_array = input('get.user_id_array');
        $users = array();
        if (!empty($user_id_array)) {
            $users = Db::name('users')->field('user_id,nickname')->where(array('user_id' => array('IN', $user_id_array)))->select();
        }
        View::assign('users',$users);
        return View::fetch();
    }

    /**
     * 发送系统消息
     * @author dyr
     * @time  2016/09/01
     */
    public function doSendMessage()
    {
        $call_back = input('call_back');//回调方法
        $text= input('post.text');//内容
        $type = input('post.type', 1);//1单人 2团队
        $admin_id = session('admin_id');
        $username = input('post.username');//个体id
        $message = array(
            'admin_id' => $admin_id,
            'message' => $text,
            'category' => 0,
            'send_time' => time()
        );
        $users = [];
        $userinfo = Db::name('users')->where(['username'=>$username])->find();
        if($type==1){
            $users[] = $userinfo['user_id'];
        }elseif($type==2){
            $users = Db::name('users')->where('find_in_set('.$userinfo['user_id'].',tjstr)')->column('user_id');
        }

        if ($type == 1) {
            //全体用户系统消息
            $message['type'] = 1;
            Db::name('Message')->add($message);
        } else {
            //个体消息
            $message['type'] = 0;
            if (!empty($users)) {
                $create_message_id = Db::name('Message')->add($message);
                foreach ($users as $key) {
                    Db::name('user_message')->add(array('user_id' => $key, 'message_id' => $create_message_id, 'status' => 0, 'category' => 0));
                }
            }
        }
        echo "<script>parent.{$call_back}(1);</script>";
        exit();
    }


    public function tjnet(){
        if(IS_AJAX){
            $username = input('username')?:'18866677777';
            $user = Db::name('users')->where(['username'=>$username])->find();
            if(!$user){
                return json(['status'=>0,'msg'=>'会员不存在']);
            }

            // 获取该会员及其下级会员
            $where = 'find_in_set('.$user['user_id'].',tjstr) or user_id='.$user['user_id'];
            $list = Db::name('users')
                ->where($where)
                ->field('user_id,username,nickname,tjr_id,depth,head_pic')
                ->order('depth asc')
                ->select()
                ->toArray();

            // 构建树状结构数据
            $data = [];
            foreach($list as $k=>$v){
                if(empty($v['nickname'])){
                    $v['nickname'] = $v['username'];
                }
                if(empty($v['head_pic'])){
                    $v['head_pic'] ='/static/img/touxiang.png';
                }
                $item = [
                    'nickname' => $v['nickname'],
                    'user_id' => $v['user_id'],
                    'head_pic' => $v['head_pic'],
                    'children' => []
                ];

                if($v['user_id'] == $user['user_id']){
                    $data = $item; // 根节点
                }else{
                    // 将当前节点添加到父节点的children中
                    $this->addNode($data, $v['tjr_id'], $item);
                }
            }

            return json(['status'=>1,'data'=>$data,'user'=>$user]);
        }
        return View::fetch();
    }
    public function getuserinfo(){
        if(IS_AJAX){
            $username = input('username')?:'18866677777';
            $user = Db::name('users')->where(['username'=>$username])->find();

            return json(['status'=>1,'user'=>$user]);
        }
    }

    /**
     * 递归添加节点到树状结构
     * @param array $data 树数据
     * @param int $pid 父ID
     * @param array $item 当前节点
     */
    private function addNode(&$data, $pid, $item){
        if($data['user_id'] == $pid){
            $data['children'][] = $item;
            return;
        }
        if(!empty($data['children'])){
            foreach($data['children'] as &$child){
                $this->addNode($child, $pid, $item);
            }
        }
    }



    public function reg1(){
        if(!IS_POST) {
            View::assign('first',Db::name('Users')->order('user_id asc')->limit(1)->value('username'));
            View::assign('username',getUsername());

            $level_arr = Db::name('user_level')->where('1=1')->select();
            View::assign('level_arr',$level_arr);
            return View::fetch();
        }else{
            $username = input('post.username');
            $password= input('post.pwd');
            $mobile = input('post.mobile');

            $user = Db::name('Users')->where(['username'=>$username])->find();
            if($user) {
                return json(['status'=>0,'msg'=>'用户名已存在']);
            }

            if(!check_mobile($mobile)){
                return json(['status'=>0,'msg'=>'请填写正确的手机号码']);
            }
//            $have = Db::name('Users')->where(['mobile'=>$mobile])->find();
//            if($have) {
//                $this->error('手机号已存在');
//            }

            $modtime = time();

            $tjr = input('post.tjr');
            $tjr = trim($tjr);
            if(empty($tjr)){
                return json(['status'=>0,'msg'=>'请填写推荐人']);
            }else{
                $rstjr = Db::name('Users')->where(['username'=>$tjr,'is_lock'=>0])->find();
                if(!$rstjr){
                    return json(['status'=>0,'msg'=>'推荐人不存在']);
                }
            }

            if ($password == '') {
                return json(['status'=>0,'msg'=>'请输入密码']);
            }

            if(strlen($password)<6 || strlen($password)>50) {
                return json(['status'=>0,'msg'=>'密码长度最低6位']);
            }

            Db::startTrans();
            $data_u=[];
            $data_u['password'] = encrypt($password);
            $data_u['reg_time'] = $modtime;
            $data_u['jihuo_time'] = $modtime;
            $data_u['last_login'] = $modtime;
            $data_u['is_lock'] = 0;
            $data_u['username'] = $username;
            $data_u['mobile'] = $mobile;

            if($rstjr){
                $data_u['tjr_id']=$rstjr['user_id'];
                $data_u['tjr_name']=$rstjr['username'];
                $data_u['depth']=$rstjr['depth']+1;
                if($rstjr['tjstr']!='') {
                    $data_u['tjstr']=$rstjr['user_id'].','.$rstjr['tjstr'];
                }else{
                    $data_u['tjstr']=$rstjr['user_id'];
                }
            }
            $user_id = Db::name('users')->insertGetId($data_u);

            if ($user_id) {
                //插入钱包
                $dataw = ['user_id'=>$user_id];
                $rs = Db::name('wallet')->insert($dataw);
                if (!$rs) {
                    Db::rollback();
                    return json(['status'=>0,'msg'=>'更新钱包失败']);
                }


                //更新团队人数
                $rs = Db::name('users')->where(array('user_id' => array('in', $data_u['tjstr'])))->inc('totalnum', 1)->update();
                if (!$rs) {
                    Db::rollback();
                    return json(['status'=>0,'msg'=>'更新团队人数失败']);
                }
                //更新推荐数量
                $rs = Db::name('users')->where(array('user_id' => $rstjr['user_id']))->inc('tjnum', 1)->update();
                if (!$rs) {
                    Db::rollback();
                    return json(['status'=>0,'msg'=>'更新直推人数失败']);
                }
                $level = input('level');
                if($level && $level!=1){
                    $curtime = getCurTime();
                    //插入升级记录
                    $insert = array();
                    $insert['username'] = $username;
                    $insert['old'] = 1;
                    $insert['new'] = $level;
                    $insert['w_time'] = $curtime;
                    $insert['desc'] = "后台修改";
                    $insert['admin_id'] = session('admin_id');
                    $rs = Db::name('level_log')->insert($insert);
                    if(!$rs){
                        return json(['status'=>0,'msg'=>'添加升级记录失败']);
                    }
                }

                Db::commit();
                return json(['status'=>1,'msg'=>'会员注册成功']);
            } else {
                Db::rollback();
                return json(['status'=>0,'msg'=>'请检查填写资料或联系客服']);
            }
        }
    }

    public function movenet(){
        if(!IS_POST) {

            return View::fetch();
        }else{
            $username = trim(input('post.username'));
            $new_tjr = trim(input('post.tjr'));

            $model = Db::name('users');
            $rsu = $model->where(array('username' => $username))->find();
            $rst = $model->where(array('username' => $new_tjr))->find();
            if(!$rsu){
                return json(['status'=>0,'msg'=>'会员不存在']);
            }
            if($rsu['user_id']==1){
                return json(['status'=>0,'msg'=>'顶点不能移动']);
            }
            if(!$rst){
                return json(['status'=>0,'msg'=>'新上级不存在']);
            }elseif($rst['is_lock']){
                return json(['status'=>0,'msg'=>'新上级已经被锁定']);
            }
            if($rst['user_id']==$rsu['user_id']){
                return json(['status'=>0,'msg'=>'不能是自己']);
            }

            if($rst['user_id']==$rsu['tjr_id']){
                return json(['status'=>0,'msg'=>'已经是上下级关系，无需移动']);
            }

            //互为上级的判断
            if ($rst['tjr_name'] == $username) {
                return json(['status'=>0,'msg'=>'两人不能互为上级']);
            }

            if($rst['tjstr']){
                $tj_ary = explode(',', $rst['tjstr']);
                if (in_array($rsu['user_id'], $tj_ary)) {
                    return json(['status'=>0,'msg'=>'新推荐人不能是自己网体下级会员！']);
                }
            }

            //查找原来网体下级会员
            Db::startTrans();
            $datau = array();
            $datau['tjstr'] = $rst['user_id'] . ',' . $rst['tjstr'];
            $datau['tjstr'] = trim($datau['tjstr'],',');
            $datau['depth'] = $rst['depth'] + 1;
            $datau['tjr_name'] = $new_tjr;
            $datau['tjr_id'] = $rst['user_id'];
            $u_save = $model->where(array('username' => $username))->update($datau);//更新移动网体的会员
            if ($u_save === false) {
                Db::rollback();
                return json(['status'=>0,'msg'=>'更新会员新上级信息失败！']);
            }

            //存放上级字符串
            $tjary = [];
            $tjary[$rsu['user_id']] =  $datau['tjstr'];

            //更新移动网体的会员的下级会员
            $rs_old_all = $model->where(" find_in_set('" . $rsu['user_id'] . "',tjstr) > 0")->order("depth asc")->select();
            if($rs_old_all){
                $num_c = $rst['depth'] - $rsu['depth'] + 1;//新的层数差
                foreach ($rs_old_all as $key => $users) {
                    if(!isset($tjary[$users['tjr_id']])){
                        Db::rollback();
                        return json(['status'=>0,'msg'=>$users['tjr_id']."上级未找到"]);
                    }
                    $datad = array();
                    $datad['user_id'] =$users['user_id'];
                    $datad['depth'] = $users['depth'] + $num_c;
                    $datad['tjstr'] = $users['tjr_id'] . ',' . $tjary[$users['tjr_id']];
                    Db::name('users')->where('user_id',$users['user_id'])->update($datad);

                    //存入上级数组
                    $tjary[$users['user_id']] = $datad['tjstr'];
                }
            }

            //更新推荐人数
            Db::name('users')->where(array('user_id' => $rsu['tjr_id']))->dec('tjnum', 1)->update();
            Db::name('users')->where(array('user_id' => $rst['user_id']))->inc('tjnum', 1)->update();

            //更新团队人数
            Db::name('users')->where(array('user_id' => array('in', $rsu['tjstr'])))->dec('totalnum', $rsu['totalnum']+1)->update();
            Db::name('users')->where(array('user_id' => array('in', $datau['tjstr'])))->inc('totalnum', $rsu['totalnum']+1)->update();

            $datau = array();
            $datau['username'] = $rsu['username'];
            $datau['old'] = $rsu['tjr_name'];
            $datau['new'] = $rst['username'];
            $datau['type'] = '推荐网';
            $datau['admin_id'] = session('admin_id');
            $datau['w_time'] = getCurTime();

            Db::name('netlog')->insert($datau);
            Db::commit();
            return json(['status'=>1,'msg'=>'修改成功！']);
        }
    }

    public function import(){
        if(IS_POST){
            set_time_limit(0);
            ini_set('memory_limit','6000M');


            /******************导入文件处理*******************/
            $tmp_file = $_FILES ['file_stu'] ['tmp_name'];
            $file_types = explode(".", $_FILES ['file_stu'] ['name']);
            $file_type = $file_types [count($file_types) - 1];

            /*判别是不是.xls文件，判别是不是excel文件*/
            if (strtolower($file_type) != "xlsx" && strtolower($file_type) != "xls") {
                $this->error('不是Excel文件，重新上传');
            }

            /*设置上传路径*/
            $savePath = './public/upload/Excel/';

            /*以时间来命名上传的文件*/
            $str = date('Ymdhis');
            $file_name = $str . "." . $file_type;

            /*是否上传成功*/
            if (!@copy($tmp_file, $savePath . $file_name)) {
                $this->error('上传失败');
            }
            $res = $this->read($savePath . $file_name, "UTF-8", $file_type);//传参,判断office2007还是office2003

            $alluser = Db::name('Users')->getField('username,user_id,is_vip,depth,tjstr,glstr,gl_depth,is_jxs,gl_left,gl_right,level');

            foreach($res as $k=>$v){
                if($k>1){//过滤第一行
                    $username=trim($v[0]);
                    $nickname= trim($v[1]);
                    $mobile = trim($v[2]);
                    $idcard = trim($v[3]);
                    $shop_username = trim($v[4]);
                    $tjr_name = trim($v[5]);
                    $gl_username = trim($v[6]);
                    $gl_pos = trim($v[7]);
                    if(empty($username)){
                        $this->error($k."行：缺少会员账号");
                    }elseif(isset($alluser[$username])){
                        $this->error($k."行：会员账号已存在");
                    }

                    if($mobile==''){
                        $this->error($k."行：缺少手机号");
                    }else{
                        if(!check_mobile($mobile)){
                            $this->error($k."行：请填写正确的手机号码");
                        }
                    }


                    if(empty($tjr_name)){
                        $this->error($k."行：缺少推荐人账号");
                    }
                    if(empty($gl_username)){
                        $this->error($k."行：缺少管理人账号");
                    }
                    if($gl_pos!='左' && $gl_pos!='右'){
                        $this->error($k."行：管理人位置只能填写：左或右");
                    }
                }
            }

            Db::startTrans();
            $curtime = getCurTime();
            foreach($res as $k=>$v){
                if($k>1){//过滤第一行
                    $username=trim($v[0]);
                    $nickname= trim($v[1]);
                    $mobile = trim($v[2]);
                    $idcard = trim($v[3]);
                    $shop_username = trim($v[4]);
                    $tjr_name = trim($v[5]);
                    $gl_username = trim($v[6]);
                    $gl_pos = trim($v[7]);
                    $is_jxs = trim($v[8]);
                    if($is_jxs=='是'){
                        $is_jxs=1;
                    }else{
                        $is_jxs=0;
                    }

                    if(isset($alluser[$username])){
                        $this->error($k."行：会员账号".$username."已存在");
                    }

                    if(!isset($alluser[$tjr_name])){
                        Db::rollback();
                        $this->error($k."行：推荐人账号不存在");
                    }elseif($alluser[$tjr_name]['level']==1){
                        Db::rollback();
                        $this->error($k."行：推荐人账号没有推广权限");
                    }

                    if(!isset($alluser[$gl_username])){
                        Db::rollback();
                        $this->error($k."行：管理人账号不存在");
                    }elseif($alluser[$gl_username]['is_vip']==0){
                        Db::rollback();
                        $this->error($k."行：管理人账号没有进双区网");
                    }
                    $rstjr = $alluser[$tjr_name];
                    $gluser = $alluser[$gl_username];
                    if($gl_pos=='左'){
                        if($gluser['gl_left']!=''){
                            Db::rollback();
                            $this->error($k."行：管理人的左区已经存在");
                        }
                    }elseif($gl_pos=='右'){
                        if($gluser['gl_right']!=''){
                            Db::rollback();
                            $this->error($k."行：管理人的右区已经存在");
                        }
                    }

                    if($shop_username!=''){
                        if(!isset($alluser[$shop_username])){
                            $this->error($k."行：所属服务中心不存在");
                        }
                        if($alluser[$shop_username]['is_jxs']==0){
                            $this->error($k."行：所属服务中心".$shop_username."并不是服务中心");
                        }
                    }
                    //密码
                    $password =  substr($mobile,-6);
                    $insert = [];
                    $insert['username'] = $username;
                    $insert['nickname'] = $nickname;
                    $insert['mobile'] = $mobile;
                    $insert['idcard'] = $idcard;
                    $insert['is_jxs'] = $is_jxs;
                    $insert['password'] = encrypt($password);
                    if($shop_username!=''){
                        $insert['shop_username'] = $shop_username;
                    }
                    $insert['reg_time'] = $curtime;

                    //其他默认信息
                    $insert['is_lock'] = 0;
                    $insert['level'] = 10;//默认vip
                    $insert['is_daoru'] = 1;
                    $insert['jihuo'] = 0; //默认未激活

                    //回填
                    $insert['huitian'] = 1;
                    $insert['htprice'] = tpCache('basic.htprice');

                    //推荐关系
                    $insert['tjr_id']=$rstjr['user_id'];
                    $insert['tjr_name']=$rstjr['username'];
                    $insert['depth']=$rstjr['depth']+1;
                    if($rstjr['tjstr']!='') {
                        $insert['tjstr']=$rstjr['user_id'].','.$rstjr['tjstr'];
                    }else{
                        $insert['tjstr']=$rstjr['user_id'];
                    }

                    //管理网
                    $insert['gl_id'] = $gluser['user_id'];
                    $insert['gl_username'] = $gl_username;
                    $insert['gl_pos'] = $gl_pos;
                    $insert['gl_depth'] = $gluser['gl_depth']+1;
                    $glstr  =trim($gluser['user_id']."-".$gl_pos.",".$gluser['glstr'],',');
                    $insert['glstr'] = $glstr;
                    $insert['is_vip'] = 1;//默认进网
                    $insert['jw_time'] = $curtime;

                    $user_id = Db::name('users')->insertGetId($insert);
                    $insert['user_id'] = $user_id;
                    if ($user_id) {
                        //插入钱包
                        $dataw = ['user_id' => $user_id];
                        $rs = Db::name('wallet')->insert($dataw);
                        if (!$rs) {
                            Db::rollback();
                            $this->error('更新钱包失败'.$k."行");
                        }

                        if ($rstjr) {
                            //更新团队人数
                            $rs = Db::name('users')->where(array('user_id' => array('in', $insert['tjstr'])))->setInc('totalnum', 1);
                            if (!$rs) {
                                Db::rollback();
                                $this->error('更新团队人数失败'.$k."行");
                            }
                            //更新推荐数量
                            $rs = Db::name('users')->where(array('user_id' => $insert['tjr_id']))->setInc('tjnum', 1);
                            if (!$rs) {
                                Db::rollback();
                                $this->error('更新直推人数失败'.$k."行");
                            }
                        }

                        //更新管理人信息
                        $save = [];
                        if($gl_pos=='左'){
                            $save['gl_left'] = $username;
                            $alluser[$gl_username]['gl_left'] = $username;//数组同步
                        }else{
                            $save['gl_right'] = $username;
                            $alluser[$gl_username]['gl_right'] = $username;
                        }
                        $rs = Db::name('users')->where(['user_id'=>$gluser['user_id']])->update($save);
                        if(!$rs){
                            Db::rollback();
                            $this->error('更新管理网上级左右区信息失败'.$k."行");
                        }

                        //不导入会员升级记录，因为未激活不拿奖
                    }else{
                        Db::rollback();
                        $this->error('会员注册失败，'.$k."行");
                    }
                    //数组赋值，为后面的人使用
                    $alluser[$username] = $insert;
                }
            }

            Db::commit();
            $this->success('导入成功',U('Users/index'));
        }else{
            return View::fetch();
        }
    }

    public function read($filename, $encode, $file_type)
    {
        vendor("Excel.PHPExcel");//引入phpexcel类(注意你自己的路径)
        vendor("Excel.PHPExcel.IOFactory");
        if (strtolower($file_type) == 'xls')//判断excel表类型为2003还是2007
        {
            vendor("Excel.PHPExcel.Reader.Excel5");
            $objReader = \PHPExcel_IOFactory::createReader('Excel5');
        } elseif (strtolower($file_type) == 'xlsx') {
            vendor("Excel.PHPExcel.Reader.Excel2007");
            $objReader = \PHPExcel_IOFactory::createReader('Excel2007');
        }
        $objReader->setReadDataOnly(true);
        $objPHPExcel = $objReader->load($filename);
        $objWorksheet = $objPHPExcel->getActiveSheet();
        $highestRow = $objWorksheet->getHighestRow();
        $highestColumn = $objWorksheet->getHighestColumn();
        $highestColumnIndex = \PHPExcel_Cell::columnIndexFromString($highestColumn);
        $excelData = array();
        for ($row = 1; $row <= $highestRow; $row++) {
            for ($col = 0; $col < $highestColumnIndex; $col++) {
                $excelData[$row][] = (string)$objWorksheet->getCellByColumnAndRow($col, $row)->getValue();
            }
        }
        return $excelData;
    }


    /**
     * 导出直推网络
     */
    public function export_tjnet()
    {

        //搜索条件
        $username = input('username');
        $user_id = Db::name('users')->where(['username'=>$username])->value('user_id');
        $where = 'find_in_set('.$user_id.',tjstr) or user_id='.$user_id;
        $wallet = logic('Wallet')->getName();

        $orderList = Db::name('Users')->where($where)->order('user_id asc')->order('depth asc')->select();
        $strTable ='<table width="700" border="1">';
        $strTable .= '<tr>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">ID</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">会员编号</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">姓名</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">手机号</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">推广人</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">推荐人姓名</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">推广人数</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">团队人数</td>';


        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">团队业绩</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">上月团队业绩</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">本月团队业绩</td>';

        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">是否服务中心</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">推广代数</td>';
        $strTable .= '</tr>';
        if(is_array($orderList)){
            $alluser = Db::name('Users')->getField('user_id,nickname');
            $last_ceng = 0;
            $ceng = 0;
            foreach($orderList as $k=>$val){
                if($k==0){
                    $ceng = 0;
                }else{
                    $ceng = $ceng+($val['depth']-$last_ceng);
                }
                $last_ceng = $val['depth'];
                $strTable .= '<tr>';
                $strTable .= '<td style="text-align:center;font-size:12px;">'.$val['user_id'].'</td>';//id
                $strTable .= '<td style="text-align:center;font-size:12px;">'.$val['username'].'</td>';//会员变化
                $strTable .= '<td style="text-align:center;font-size:12px;">'.$val['nickname'].'</td>';//姓名
                $strTable .= '<td style="text-align:center;font-size:12px;">'.$val['mobile'].'</td>';//手机号
                $strTable .= '<td style="text-align:center;font-size:12px;">'.$val['tjr_name'].'</td>';//推荐人
                $strTable .= '<td style="text-align:center;font-size:12px;">'.$alluser[$val['tjr_id']].'</td>';//推荐人姓名
                $strTable .= '<td style="text-align:center;font-size:12px;">'.$val['tjnum'].'</td>';//推广人数
                $strTable .= '<td style="text-align:center;font-size:12px;">'.$val['totalnum'].'</td>';//团队人数

                $strTable .= '<td style="text-align:center;font-size:12px;">'.$val['team_yeji'].'</td>';//团队业绩

                $modtime = getCurTime();
                $down_user_ids = db('users')->where('find_in_set('.$val['user_id'].',tjstr)')->column('user_id');
                //上月1号
                $s_time = mktime(0, 0, 0, date('m', $modtime) - 1, 1, date('Y', $modtime));
                //本月1号
                $e_time = strtotime(date('Y-m-1',$modtime));
                $last_month_yeji =db('order')
                    ->where('order_status','in',[1,2,3])
                    ->where('pay_time','between time',[$s_time,$e_time])
                    ->where('user_id','in',$down_user_ids)
                    ->sum('total_shop_price');
                $month_yeji = db('order')
                    ->where('order_status','in',[1,2,3])
                    ->where('pay_time','egt',$e_time)
                    ->where('user_id','in',$down_user_ids)
                    ->sum('total_shop_price');

                $strTable .= '<td style="text-align:center;font-size:12px;">'.$last_month_yeji.'</td>';//复销总个人业绩
                $strTable .= '<td style="text-align:center;font-size:12px;">'.$month_yeji.'</td>';//上月复销总业绩

                $strTable .= '<td style="text-align:center;font-size:12px;">'.($val['is_fuwu']?'是':'否').'</td>';//是否服务中心
                $strTable .= '<td style="text-align:center;font-size:12px;">'.$ceng.'</td>';

                $strTable .= '</tr>';
            }
        }
        $strTable .='</table>';
        unset($orderList);
        downloadExcel($strTable,'users');
        exit();
    }
    /**
     * 导出双区网络
     */
    public function export_glnet()
    {
        //搜索条件
        $username = input('username');
        $user_id = Db::name('users')->where(['username'=>$username])->value('user_id');
        $where = 'find_in_set("'.$user_id.'-左",glstr) or find_in_set("'.$user_id.'-右",glstr) or username="'.$username.'"';
        $wallet = logic('Wallet')->getName();

        $orderList = Db::name('Users')->where($where)->order('user_id asc')->select();
        $strTable ='<table width="700" border="1">';
        $strTable .= '<tr>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">ID</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">会员编号</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">姓名</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">手机号</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">管理人</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">管理人姓名</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">左区总套数</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">右区总套数</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">左区月总套数</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">右区月总套数/td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">左区日总套数</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">右区日总套数</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">是否激活</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">注册日期</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">激活时间</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">是否服务中心</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">所属服务中心</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">层数</td>';
        $strTable .= '</tr>';
        if(is_array($orderList)){
            $alluser = Db::name('Users')->getField('user_id,nickname');
            $last_ceng = 0;
            $ceng = 0;
            foreach($orderList as $k=>$val){

                if($k==0){
                    $ceng = 0;
                }else{
                    $ceng = $ceng+($val['gl_depth']-$last_ceng);
                }
                $last_ceng = $val['gl_depth'];
                $strTable .= '<tr>';
                $strTable .= '<td style="text-align:center;font-size:12px;">'.$val['user_id'].'</td>';//id
                $strTable .= '<td style="text-align:center;font-size:12px;">'.$val['username'].'</td>';//会员变化
                $strTable .= '<td style="text-align:center;font-size:12px;">'.$val['nickname'].'</td>';//姓名
                $strTable .= '<td style="text-align:center;font-size:12px;">'.$val['mobile'].'</td>';//手机号
                $strTable .= '<td style="text-align:center;font-size:12px;">'.$val['gl_username'].'</td>';//管理人
                $strTable .= '<td style="text-align:center;font-size:12px;">'.$alluser[$val['gl_id']].'</td>';//管理人姓名
                $strTable .= '<td style="text-align:center;font-size:12px;">'.$val['gl_left_totalnum'].'</td>';//左区总套数
                $strTable .= '<td style="text-align:center;font-size:12px;">'.$val['gl_right_totalnum'].'</td>';//右区总套数
                $strTable .= '<td style="text-align:center;font-size:12px;">'.$val['gl_left_monthnum'].'</td>';//左区月总套数
                $strTable .= '<td style="text-align:center;font-size:12px;">'.$val['gl_right_monthnum'].'</td>';//右区月总套数
                $strTable .= '<td style="text-align:center;font-size:12px;">'.$val['gl_left_daynum'].'</td>';//左区日总套数
                $strTable .= '<td style="text-align:center;font-size:12px;">'.$val['gl_right_daynum'].'</td>';//右区日总套数
                $reg_time = '';
                if($val['reg_time']){
                    $reg_time = date('Y-m-d H:i:s',$val['reg_time']);
                }
                $strTable .= '<td style="text-align:center;font-size:12px;">'.$reg_time.'</td>';//注册日期
                if($val['jihuo']==1){
                    $strTable .= '<td style="text-align:left;font-size:12px;">是 </td>';//是否激活
                }else{
                    $strTable .= '<td style="text-align:left;font-size:12px;">否 </td>';//是否激活
                }
                $jhtime = '';
                if($val['jihuo_time']){
                    $jhtime = date('Y-m-d H:i:s',$val['jihuo_time']);
                }
                $strTable .= '<td style="text-align:left;font-size:12px;">'.$jhtime.' </td>';//激活时间


                $strTable .= '<td style="text-align:center;font-size:12px;">'.($val['is_jxs']?'是':'否').'</td>';//是否服务中心
                $strTable .= '<td style="text-align:center;font-size:12px;">'.$val['shop_username'].'</td>';//所属服务中心
                $strTable .= '<td style="text-align:center;font-size:12px;">'.$ceng.'</td>';

                $strTable .= '</tr>';
            }
        }
        $strTable .='</table>';
        unset($orderList);
        downloadExcel($strTable,'users');
        exit();
    }

    //删除会员
    public function delUser(){
        $id_arr = input('ids/a');
        //$id_arr = explode(',',$user_ids);
        Db::startTrans();
        $list = Db::name('users')->where('user_id','in',$id_arr)->select();
        $last_prize_time = Db::name('prize')->order('id desc')->value('w_time');
        $logic = new OrderLogic();
        foreach($list as $v){
            //网体下有人的不可以删
            if($v['totalnum']>0 || $v['gl_left_totalnum']>0 || $v['gl_right_totalnum']>0){
                return json(['status'=>0,'msg'=>'会员'.$v['username'].'网体下存在会员不可删除']);
                continue;
            }
            if($v['reg_time']<$last_prize_time){
                return json(['status'=>0,'msg'=>'会员'.$v['username'].'在结算后注册，不可删除']);
            }
            if($v['level']>1){
                return json(['status'=>0,'msg'=>'会员'.$v['username'].'非免费会员，不可删除']);
            }
            $where = [];
            $where[] = ['user_id','=',$v['user_id']];
            $where[] = ['order_status','in',[1,2,3,4]];
            $orders = Db::name('order')->where($where)->select()->toArray();
            if($orders){
                return json(['status'=>0,'msg'=>'会员'.$v['username'].'存在订单，不可删除']);
            }
            $wallet = Db::name('wallet')->where(['user_id'=>$v['user_id']])->find();
            if($wallet['money']>0 || $wallet['shouyi']>0 || $wallet['gouwuquan']>0){
                return json(['status'=>0,'msg'=>'会员'.$v['username'].'存在钱包数据，不可删除']);
            }

            Db::name('users')->delete($v['user_id']);
            //添加到删除表
            Db::name('users_del')->insert($v);
            //查询会员订单
            $orders = Db::name('order')->where(['user_id'=>$v['user_id']])->select()->toArray();
            if($orders){
                foreach($orders as $order){
                    $data = $logic->cancel_userorder($order);
                    if($data['status']!=1){
                        return json(['status'=>0,'msg'=>$data['msg']]);
                    }
                }
            }
        }
        Db::commit();
        return json(['status'=>1,'msg'=>'删除成功!']);
    }



    /*
     * 充值
     */
    public function recharge(){
        if (IS_POST) {
            $user_id = input('user_id', '','trim');
            $user = Db::name('Users')->where(['user_id'=>$user_id,'is_lock'=>0])->find();
            $username = $user['username'];
            $number	= input('number', '','floatval');
            $money_type	= input('money_type', '','trim');
            $memo = input('memo', 'trim');

            if($number==0) {
                return json(['status'=>0,'msg'=>'充值金额不能等于0']);
            }
            if(!$username) {
                return json(['status'=>0,'msg'=>'请输入会员手机号']);
            }
            if(!$user){
                return json(['status'=>0,'msg'=>'会员不存在或者已冻结']);
            }
            Db::startTrans();
            //插入充值记录
            $data = [];
            $data['user_id'] = $user['user_id'];
            $data['username'] = $username;
            $data['money'] = $number;
            $data['admin_id'] = session('admin_id')??0;
            $data['money_type'] = $money_type;
            $data['w_time'] = time();
            $data['memo'] = $memo;
            $rs = Db::name('recharge_log')->insert($data);
            if(!$rs){
                Db::rollback();
                return json(['status'=>0,'msg'=>'插入充值记录失败']);
            }
            //更新钱包
            $result=qianbao($user['user_id'],$number,$money_type,'管理员充单',$memo);
            if($result['status']){
                Db::commit();
                return json(['status'=>1,'msg'=>'充值成功!']);
            }else{
                Db::rollback();
                return json(['status'=>0,'msg'=>$result['msg']]);
            }
        }else{
            $username		= input('username','', 'trim');
            View::assign('username',$username);
            return View::fetch();
        }
    }

    public function excel(){
        $map = [];
        if(input('user_id')){
            $map['u.user_id'] = input('user_id');
        }
        if(input('username')){
            $map['u.username'] = input('username');
        }
        if(input('level')){
            $map['u.level'] = input('level');
        }
        if(input('time_start') && input('time_end')){
            $time_start = strtotime(input('time_start'));
            $time_end = strtotime(input('time_end'));
            $map['reg_time'] = ['between',[$time_start,$time_end]];
        }
        $count = Db::name('users')->alias('u')->where($map)->count();

        $field = 'u.user_id,u.username,u.mobile,u.nickname,u.level,u.level1,u.tjr_name,u.gl_username,u.is_lock,u.email,u.reg_time,w.money,w.shouyi,w.gouwuquan';
        $list = Db::name('users')
            ->alias('u')
            ->join('wallet w','u.user_id=w.user_id')
            ->field($field)
            ->where($map)
            ->order('u.user_id desc ')
            ->select();
        $level_arr = Db::name('user_level')->column('level_name','rank');
        $level1_arr = Db::name('user_level1')->column('level_name','rank');
        $title = ['ID','会有编号','姓名','会有级别','管理级别','团队业绩','手机号','推广人','注册时间','电子币','收益','购物券'];
        $arr = [];
        foreach($list as $k=>$v){
            $v['level_name'] = $level_arr[$v['level']];
            $v['level1_name'] = $level1_arr[$v['level1']];
            $v['reg_time'] = date('Y-m-d H:i:s',$v['reg_time']);
            $list[$k] = $v;
            $down_user_ids = Db::name('users')->where('find_in_set('.$v['user_id'].',tjstr)')->column('user_id');
            $team_yeji = Db::name('order')
                ->where('order_status','in',[1,2,3,4])
                ->where('user_id','in',$down_user_ids)
                ->sum('total_shop_price');

            $arr = [
                $v['user_id'],$v['username'],$v['nickname'],$v['level_name'],$v['level1_name'],$team_yeji,$v['mobile'],$v['tjr_name'],$v['reg_time'],$v['money'],$v['shouyi'],$v['gouwuquan']
            ];
            $data[] = $arr;
        }
        return json(['code'=>0,'msg'=>'查询成功','count'=>$count,'data'=>$data,'title'=>$title]);
        //dump($title);
        //dump($data);exit;
        $this->export_excel($title,$data);
    }

    public function chooseuser(){
        if(IS_POST){
            $id = input('post.id/d');
            $info = Db::name('users')->where('user_id',$id)->find();
            if(empty($info['nickname'])){
                $info['nickname'] = $info['username'];
            }
            return json(['status'=>1,'data'=>$info]);
        }else{
            return View::fetch();
        }
    }

    public function changeFuwuStatus(){
        $user_id = input('user_id');
        $is_fuwu = Db::name('users')->where('user_id',$user_id)->value('is_fuwu');
        Db::name('users')->where('user_id',$user_id)->update(['is_fuwu'=>$is_fuwu?0:1]);
        return json(['status'=>1,'msg'=>'修改成功']);
    }
}